<script setup lang="ts">
import { useStoreDict } from '@/store/modules/dict'
import { useCfgProptyAdd, useCfgProptyDel, useGetCfgDetail } from '@fl/api/man-api/pricing-tool'
import { cloneDeep } from 'lodash-es'
import { computed, nextTick, ref, toRefs } from 'vue'

const props = withDefaults(defineProps<{
    limit?: number
    row?: any
}>(), {
    limit: 20,
})

const { limit, row } = toRefs(props)

const visible = defineModel<boolean>()

const { dicts } = useStoreDict()

const tableData = ref<any>([])
const tableRef = ref()

// 属性配置 详情回显
const params = computed(() => ({ calcCategoryId: row.value.calcCategoryId }))
const { data, isLoading } = useGetCfgDetail(params)

// 是否存在计算项详情，0：否，1：是
const hasInfo = computed(() => {
    return row.value?.hasDataList === 1
})

watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value)
    }
})

const { mutate } = useCfgProptyDel()
function doDel({ $index, row }) {
    console.log($index, row)

    ElMessageBox.confirm('该操作将永久删除，是否继续?', '提示', { type: 'warning' })
        .then(() => {
            if (row?.id) {
                mutate({ propertyId: row?.id }, {
                    onSuccess: () => {
                        ElMessage({ message: '操作成功', type: 'success' })
                    },
                })
            }
            else {
                ElMessage({ message: '操作成功', type: 'success' })
            }

            tableData.value.splice($index, 1)
        })
}

const { mutate: mutateAdd } = useCfgProptyAdd()
function doSave() {
    const target = cloneDeep(tableData.value)
    if (!target.length) {
        ElMessage.error(`请添加属性`)
        return
    }

    // 重复校验
    const noRepeat = new Set([...target.map((v: any) => v.name)])
    if (target.length !== noRepeat.size) {
        ElMessage.error(`存在重复属性名称`)
        return
    }

    const isEnpty = target.some((v: any) => !v.name)
    if (isEnpty) {
        ElMessage.error(`请填写完整再保存`)
        return
    }

    const hasCalc = tableData.value.some((v: any) => v.calcField === 1)
    if (!hasCalc) {
        ElMessage.error(`必须要有一个属性为计算项`)
        return
    }

    mutateAdd(target, {
        onSuccess: () => {
            ElMessage({ message: '操作成功', type: 'success' })
            cancel()
        },
    })
}

function doAdd() {
    const len = tableData.value.length
    if (tableData.value.length >= limit.value) {
        ElMessage.error(`最多添加${limit.value}条数据！`)
        return
    }

    let isNext = true
    const target = tableData.value[len - 1]
    // 校验上条数据 是否填写完整
    if (len && /^\s*$/.test(target.name)) {
        isNext = false
    }

    if (!isNext) {
        ElMessage.error(`请填写完整第${len}条数据`)
        return
    }

    const models = tableData.value.map((v: any) => v.name)
    const arr = models.slice(0, models.length - 1)
    if (len > 1 && arr.includes(target.name)) {
        ElMessage.error(`第${len}条数据属性名称已存在`)
        return
    }

    tableData.value.push({
        calcCategoryId: row.value.calcCategoryId,
        calcField: 0,
        name: '',
        optionField: 0,
        searchField: 0,
        type: 0,
        typeRef: '',
    })

    if (tableData.value.length > 5) {
        nextTick(() => {
            tableRef.value.setScrollTop(len * 300)
        })
    }
}

function cancel() {
    visible.value = false
}

function typeChange(val, { $index }) {
    if (val === 2) {
        tableData.value[$index].typeRef = 'jc_zjgj_unit'
        tableData.value[$index].searchField = 0
        tableData.value[$index].calcField = 0
    }
}

// 当前配置只允许添加一项计算项
async function calcChange(val, { $index }) {
    const target = tableData.value.filter((v: any) => v.calcField === 1)
    if (target.length > 1) {
        ElMessage.error(`已存在计算项`)
        await nextTick()
        tableData.value[$index].calcField = 0
    }

    // 计算项录入方式只能是数字输入
    if (val === 1) {
        tableData.value[$index].type = 1
    }
}
</script>

<template>
    <el-dialog v-model="visible"
               title="配置属性"
               close-on-press-escape
               @cancel="cancel"
               @closed="cancel"
    >
        <el-table ref="tableRef"
                  v-loading="isLoading"
                  :data="tableData"
                  stripe
                  height="300"
        >
            <el-table-column label="序号"
                             type="index"
                             width="60"
            />

            <el-table-column label="属性名称"
                             width="200"
            >
                <template #default="scope">
                    <el-input v-model="scope.row.name"
                              maxlength="20"
                              placeholder="请输入"
                              clearable
                              :disabled="scope.row.id && hasInfo"
                    />
                </template>
            </el-table-column>

            <el-table-column label="录入方式"
                             width="130"
            >
                <template #default="scope">
                    <el-select v-model="scope.row.type"
                               :disabled="scope.row.id && hasInfo || scope.row.calcField === 1"
                               @change="typeChange($event, scope)"
                    >
                        <el-option v-for="item in dicts.jc_zjgj_input_type"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="Number(item.value)"
                        />
                    </el-select>
                </template>
            </el-table-column>

            <el-table-column label="是否计算项"
                             width="100"
            >
                <template #default="scope">
                    <el-select v-model="scope.row.calcField"
                               :disabled="scope.row.type === 2 || (scope.row.id && hasInfo)"
                               @change="calcChange($event, scope)"
                    >
                        <el-option v-for="item in dicts.jc_zjgj_boolean"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="Number(item.value)"
                        />
                    </el-select>
                </template>
            </el-table-column>

            <el-table-column label="是否搜索项"
                             width="100"
            >
                <template #default="scope">
                    <el-select v-model="scope.row.searchField"
                               :disabled="scope.row.type === 2 || (scope.row.id && hasInfo)"
                    >
                        <el-option v-for="item in dicts.jc_zjgj_boolean"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="Number(item.value)"
                        />
                    </el-select>
                </template>
            </el-table-column>

            <el-table-column label="是否计算项标题"
                             width="130"
            >
                <template #default="scope">
                    <el-select v-model="scope.row.optionField"
                               :disabled="scope.row.id && hasInfo"
                    >
                        <el-option v-for="item in dicts.jc_zjgj_boolean"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="Number(item.value)"
                        />
                    </el-select>
                </template>
            </el-table-column>

            <el-table-column label="操作"
                             width="80"
            >
                <template #default="scope">
                    <el-button v-if="!scope.row.id || !hasInfo"
                               link
                               type="primary"
                               @click="doDel(scope)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-button class="mt-20"
                   type="primary"
                   plain
                   @click="doAdd"
        >
            + 新增属性
        </el-button>

        <template #footer>
            <div class="text-center w-full">
                <el-button @click="cancel">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="doSave"
                >
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss"></style>
